package com.delivery.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.delivery.constant.JwtClaimsConstant;
import com.delivery.constant.MessageConstant;
import com.delivery.dto.UserLoginDTO;
import com.delivery.entity.User;
import com.delivery.exception.LoginFailedException;
import com.delivery.mapper.UserMapper;
import com.delivery.properties.JwtProperties;
import com.delivery.properties.WeChatProperties;
import com.delivery.service.UserService;
import com.delivery.utils.HttpClientUtil;
import com.delivery.utils.JwtUtil;
import com.delivery.vo.UserLoginVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.Map;

@Service
public class UserServiceImpl implements UserService {

    @Autowired
    private UserMapper userMapper;

    @Autowired
    private JwtProperties jwtProperties;

    @Autowired
    private WeChatProperties weChatProperties;

    @Override
    public UserLoginVO login(UserLoginDTO userLoginDTO) {

        Map<String, String> paramMap = new HashMap<>();
        paramMap.put("appid", weChatProperties.getAppid());
        paramMap.put("secret", weChatProperties.getSecret());
        paramMap.put("js_code", userLoginDTO.getCode());
        paramMap.put("grant_type", "authorization_code");

        String resultString = HttpClientUtil.doGet("https://api.weixin.qq.com/sns/jscode2session", paramMap);
        JSONObject jsonObject = JSONObject.parseObject(resultString);

        String openid = jsonObject.getString("openid");
        if (openid == null) {
            throw new LoginFailedException(MessageConstant.LOGIN_FAILED);
        }

        // 检查 user 表，如果存在，则直接登录，不存在则自动注册
        User user = userMapper.selectByOpenid(jsonObject.getString("openid"));
        if (user == null) {
            user = new User();
            user.setOpenid(jsonObject.getString("openid"));
            user.setCreateTime(LocalDateTime.now());
            user.setName("未命名");
            userMapper.insert(user);
        }

        Map<String, Object> claims = new HashMap<>();
        claims.put(JwtClaimsConstant.USER_ID, user.getId());

        // 生成 token
        String token = JwtUtil.createJWT(jwtProperties.getUserSecretKey(),
                jwtProperties.getUserTtl(), claims);

        return UserLoginVO.builder()
                .id(user.getId())
                .openid(user.getOpenid())
                .token(token)
                .build();
    }
}
